package com.guoxin.zuche.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Calendar;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;


import android.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.telephony.TelephonyManager;

public class Util {
	private static ProgressDialog progressDialog;
	private static Activity activity;
	private static Boolean isOK = false;
//	public static  ImageService imageService = null;
	
	private static final double EARTH_RADIUS = 6378137;
    private static double rad(double d){
       return d * Math.PI / 180.0;
    }
	 public static double getDistance(double lat1, double lng1, double lat2, double lng2){
        double radLat1 = rad(lat1);
        double radLat2 = rad(lat2);
        double a = radLat1 - radLat2;
        double b = rad(lng1) - rad(lng2);
        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2) + 
         Math.cos(radLat1)*Math.cos(radLat2)*Math.pow(Math.sin(b/2),2)));
        s = s * EARTH_RADIUS;
        s = Math.round(s * 10000) / 10000;
        return s;
     }
	 
		/**
		 * 娴佽浆鎹簩杩涘埗
		 * @author 钁ｆ案锟�
		 * @param inputStream
		 * @return
		 * @throws Exception
		 */
	public static byte[] readStream(InputStream inputStream) throws Exception{
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = 0 ;
		while((len = inputStream.read(buffer)) != -1){
			outputStream.write(buffer, 0, len);
		}
		outputStream.close();
		inputStream.close();
		return outputStream.toByteArray();
	}
	/**
	 * 闅愯棌绛夊緟杩涘害锟�
	 * @author 钁ｆ案锟�
	 * @param
	 */
	public static void hideProgressDialog() {
		activity.runOnUiThread(new Thread() {
			public void run() {
				if (progressDialog != null && progressDialog.isShowing()) {
					progressDialog.hide();
				}
			}
		});
	}
	/**
	 * 鏄剧ず绛夊緟杩涘害锟�
	 * @author 钁ｆ案锟�
	 * @param a
	 */
	public static void showProgressDialog(final Activity a) {
		a.runOnUiThread(new Thread() {
			public void run() {
				activity = a;
				progressDialog = ProgressDialog.show(activity,"", "锟斤拷锟斤拷锟斤拷...", true,true);
			}
		});
	}
	/**
	 * 鍒涘缓锟�锟斤拷鎸囧畾宸ヤ綔绾跨▼鏁伴噺鐨勭嚎绋嬫睜锟�
	 * 姣忓綋鎻愪氦锟�锟斤拷浠诲姟灏卞垱寤轰竴涓伐浣滅嚎绋嬶紝濡傛灉宸ヤ綔绾跨▼鏁伴噺杈惧埌绾跨▼姹犲垵濮嬬殑锟�锟斤拷鏁帮紝鍒欏皢鎻愪氦鐨勪换鍔″瓨鍏ュ埌姹犻槦鍒椾腑锟�
	 */
	public static ThreadPoolExecutor execute = (ThreadPoolExecutor)Executors.newFixedThreadPool(3);
	/**
	 * 鑾峰緱IMEI
	 * @author 钁ｆ案锟�
	 * @param activity
	 * @return 
	 * @param 
	 */
	public static String getIMEI(Activity activity){
		TelephonyManager tm = (TelephonyManager) activity.getSystemService(Context.TELEPHONY_SERVICE);
		return tm.getDeviceId();
	}
	/**	 
	 * * 寰楀埌褰撳墠鏃堕棿鐨勬椂闂存埑	 
	 * * 	 
	 * * @return 褰撳墠鏃堕棿锟� 
	 * */	
	public static String getNowTimestamp() {
		long curTime = System.currentTimeMillis();		
		return String.valueOf(curTime);	
	}
	/**
	 * @author 钁ｆ案锟�
	 * @param urlstr
	 * @return 鍥剧墖鐨凚itmap
	 * @param
	 */
	public static Bitmap downloadImage(String strurl ,Context context,int default_image,String type,String host){ 
		Bitmap bmImg = null;
		String urlstr = strurl+type;
		if(!"".equals(strurl)&&strurl!=null){
			  InputStream is = null;
	          try { 
	        	  	int apn = APNManage.getApnType();
  					String url_apn = urlstr;
  					url_apn = Util.url_apn_download(url_apn,apn,host);
	        	  	
  					URL url= new URL(url_apn); 
	        	  	HttpURLConnection conn= (HttpURLConnection)url.openConnection(); 
	               	conn.setConnectTimeout(5*1000);
	            	if(apn == APNManage.CMWAP_APN){
    					conn.setRequestProperty("X-Online-Host",host);
    				}
	   			  	conn.setDoInput(true);
	   				conn.setDoOutput(true);
	   			if(conn.getResponseCode()==200){
	   				is = conn.getInputStream(); 
	   				if(is!=null){
	   					bmImg = BitmapFactory.decodeStream(is); 
	   				}
	   			}else{
   					bmImg = BitmapFactory.decodeResource(context.getResources(),default_image);
   				}
	          } catch (Exception e) {
	               e.printStackTrace(); 
	          }finally{
	        	  if(is!=null){
	        		try {
						is.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
	        	  }
	          }
		}else{
			bmImg = BitmapFactory.decodeResource(context.getResources(),default_image);
		}
	    return bmImg;
	} 
	public static String url_apn_download(String url,int apn,String host) throws MalformedURLException{
		String apn_url = "";
		//鍘绘帀host閮ㄥ垎
		URL u= new URL(url); 
		String hostName = u.getHost();
		if(apn==APNManage.CMWAP_APN){
			apn_url =url.replace(hostName, "10.0.0.172:80");
		}else{
			apn_url = url;
		}
		return apn_url;
	}
	public static HttpURLConnection getHttpURLConnection(String url){
		//鍘绘帀host閮ㄥ垎
		HttpURLConnection conn = null;
		String apn_url="";
		try {
			URL u = new URL(url); 
			String hostName = u.getHost();
			if(APNManage.getApnType()==APNManage.CMWAP_APN){
				apn_url =url.replace(hostName, "10.0.0.172:80");
			}else{
				apn_url = url;
			}
			URL u1 = new URL(apn_url); 
			conn = (HttpURLConnection)u1.openConnection(); 
			if(APNManage.getApnType()==APNManage.CMWAP_APN){
				conn.setRequestProperty("X-Online-Host", hostName);
			}
			conn.setConnectTimeout(8 * 1000);
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return conn;
	}
	
	public static boolean isMobile_spExist(Activity activity,String packageName) {
		PackageManager manager = activity.getPackageManager();
		List<PackageInfo> pkgList = manager.getInstalledPackages(0);
		for (int i = 0; i < pkgList.size(); i++) {
			PackageInfo pI = pkgList.get(i);
			if (pI.packageName.equalsIgnoreCase(packageName))
				return true;
		}

		return false;
	}
	
	/**
	 * 鍒ゆ柇缃戠粶鏄惁鍙敤
	 * @author 钁ｆ案锟�
	 * @param context
	 * @return
	 */
	public static boolean isNetworkConnected(final Context context){   
		ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);   
		NetworkInfo network = cm.getActiveNetworkInfo();   
		if(network != null){   
			return network.isAvailable();
		}else{
			Builder b = new AlertDialog.Builder(context)
						.setTitle("璁剧疆缃戠粶").setMessage("缃戠粶閿欒,璇锋鏌ユ墜鏈虹綉缁滆缃垨灏濊瘯閲嶅惎鎵嬫満");
			b.setPositiveButton("璁剧疆缃戠粶", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) { 
					Intent mIntent = new Intent("/");
					ComponentName comp = new ComponentName("com.android.settings","com.android.settings.WirelessSettings");
					mIntent.setComponent(comp);
					mIntent.setAction("android.intent.action.VIEW");
					context.startActivity(mIntent);
					isOK =  isNetworkConnected(context);
				}
			}).setNeutralButton("鍙栨秷", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {
					((Activity) context).finish();
					dialog.cancel();
				}
			}).show();

		}
		return isOK;
	}
	public static String url_apn(String url,int apn,String host){
		  String apn_url = "";
		  switch (apn) {
		  	case APNManage.CMWAP_APN:
		  		apn_url = "http://10.0.0.172:80"+url;
			  break;
			case APNManage.CMNET_APN:
				apn_url = "http://"+host+url;
				break;
			case APNManage.WIFI_APN:
				apn_url = "http://"+host+url;
				break;
			default:
				apn_url = "http://"+host+url;
				break;
			}
		return apn_url;
	}
	
	public static Integer getCurSysTime(){
		Calendar calendar = Calendar.getInstance();
		int hour = calendar.get(Calendar.HOUR_OF_DAY);
		return hour;
	}
	public static String mEncode(String content) {
		try {
			content = URLEncoder.encode(content, "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return content;
	}
	
	 /**
	  * 鍒ゆ柇鏄惁涓虹┖ //true 浠ｈ〃str 涓簄ull
	  */
	public static Boolean isNull(String str){
		if(str!=null&&!str.equals("")&&str!=""&&!str.equals("null")){
			return false;
		}
		return true;
	}
}
